/*
 * Copyright (C) 2016 yixun All Rights Reserved.
 * 
 * ValidateCodeServiceImpl.java
 */
package com.yixun.qfbao.service.impl;

import com.yixun.common.page.Page;
import com.yixun.qfbao.enums.QfSmsTemplateEnum;
import com.yixun.qfbao.mapper.SmsHistoryMapper;
import com.yixun.qfbao.mapper.ValidateCodeMapper;
import com.yixun.qfbao.model.Company;
import com.yixun.qfbao.model.PartnerInfo;
import com.yixun.qfbao.model.ValidateCode;
import com.yixun.qfbao.model.dto.CompanyDto;
import com.yixun.qfbao.model.dto.PartnerInfoDto;
import com.yixun.qfbao.model.dto.SmsHistoryDto;
import com.yixun.qfbao.model.dto.ValidateCodeDto;
import com.yixun.qfbao.model.enums.DelFlagEnum;
import com.yixun.qfbao.model.enums.SMSTypeEnum;
import com.yixun.qfbao.model.enums.SendStatusEnum;
import com.yixun.qfbao.model.enums.SystemIdEnum;
import com.yixun.qfbao.service.CompanyService;
import com.yixun.qfbao.service.PartnerInfoService;
import com.yixun.qfbao.service.SmsSettingService;
import com.yixun.qfbao.service.ValidateCodeService;
import com.yixun.qfbao.util.RegexUtils;
import com.yixun.qfbao.util.SMSUtil;
import com.yixun.qfbao.util.exception.TServerException;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;


/**
 * [文件名称]<br>
 * ValidateCodeServiceImpl.java<br>
 * <br>
 * [文件描述]<br>
 * 手机验证码 service interface impl<br>
 * <br>
 * [修改记录]<br>
 * 2016-01-11 11:24:14 创建 陶俊代码生成器<br>
 * 
 * @author 陶俊代码生成器
 * @version 1.00
 */
@Service("validateCodeService")
public class ValidateCodeServiceImpl implements ValidateCodeService {
	private static Logger logger = LoggerFactory.getLogger(ValidateCodeServiceImpl.class);
	@Autowired
	private ValidateCodeMapper mapper;
	@Autowired
	private SmsHistoryMapper smsHistoryMapper;
	@Autowired
	private SMSUtil smsUtil;
	@Autowired
	private PartnerInfoService partnerInfoService;
	@Autowired
	private CompanyService companyService;
	@Autowired
	private SmsSettingService smsSettingService;
	
	SimpleDateFormat format = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
	
	/**
	 * @param entity 搜索条件
	 * @param begin 分页开始行数[不包含]
	 * @param end 分页结束行数[包含]
	 * @return 分页记录
	 */
	@Transactional(readOnly = true)
	public Page<ValidateCode> getPageModel(ValidateCodeDto entity,int begin,int end){
		Integer total = mapper.count(entity);
		List<ValidateCode> rows = mapper.list(entity,begin,end);
	    Page<ValidateCode> msr = new Page<ValidateCode>(total, rows);
		return msr;
	}

	/**
	 * 查询列表
	 * @param entity 搜索条件
	 * @return 分页记录
	 */
	public List<ValidateCode> selectListByDto(ValidateCodeDto entity){
		return mapper.selectListByDto(entity);
	}
	
	/**
	 * 查询单个
	 * @param entity 搜索条件
	 * @return 分页记录
	 */
	public ValidateCode selectByDto(ValidateCodeDto entity){
		return mapper.selectByDto(entity);
	}
	
	/**
	 * @param id 搜索条件
	 * @return 分页记录
	 */
	public ValidateCode selectById(Long id){
		if(id!=null){
			return mapper.selectById(id);
		}
		return null;
	}
	/**
	 * @param entity 新增记录的详细信息
	 * @return 新增行数
	 */
	public int create(ValidateCodeDto entity) {
		entity.setCreateTime(Calendar.getInstance().getTime());
		return mapper.add(entity);
	}

	/**
	 * @param entity 更新记录的详细信息
	 * @return 更新行数
	 */
	public int update(ValidateCodeDto entity) {
		entity.setUpdateTime(Calendar.getInstance().getTime());
		return mapper.edit(entity);
	}
    
	/**
	 * @param entity 待删除的记录信息
	 * @return 删除行数
	 */
	public int destroy(ValidateCodeDto entity) {
		return mapper.del(entity);
	}
	
	/**
	 * @param entity 新增或更新
	 * @return 新增行数
	 */
	public int saveOrUpdate(ValidateCodeDto entity) {
		if(entity!=null&&entity.getId()!=null){
			return update(entity);
		}else{
			create(entity);
			return 1;
		}
	}
	
	/**
	 * @param entity 根据pojo搜索如果主键为空则返回它本身
	 * @return 一行记录或本身
	 */
	@Override
	public ValidateCode selectBy(ValidateCode entity) {
		if(entity!=null&&entity.getId()!=null){
			return mapper.selectById(entity.getId());
		}
		return entity;
	}

	/**
	 * 验证码是否有效，三分钟内
	 * @param phone
	 * @param code;
	 * @return
	 */
	@Override
	public boolean isValidate(String phone,String code){
		//取最新 的那一条
		boolean flag = false;
		List<ValidateCode> list = mapper.selectNewCodeByPhone(phone);
		if(list != null && list.size() > 0){
			if(list.get(0).getValidateCode().equals(code)){
				flag = (System.currentTimeMillis() - (list.get(0).getCreateTime()).getTime()) / 1000 < 180;
			}
		}
		return flag;
	}

	@Async
	@Transactional
	public void deleteValidate(String phone){
		List<ValidateCode> list = mapper.selectNewCodeByPhone(phone);
		if(list != null && list.size() > 0){
			ValidateCode validateCode = list.get(0);
			validateCode.setStatus("0");
			validateCode.setUpdateTime(Calendar.getInstance().getTime());
			mapper.edit(validateCode);
		}

	}

	/**
	 *发送验证码
	 * @param partnerInfo
	 * @return
	 */
	@Override
	public String sendValidateCodeForPwd(PartnerInfoDto partnerInfo,String companyUuid){
		String domain = partnerInfo.getDomain();
		if(RegexUtils.domainRegex(partnerInfo.getDomain())){
			domain = partnerInfo.getDomain().substring(partnerInfo.getDomain().indexOf("//")+2,partnerInfo.getDomain().indexOf("."));
		}
		Company company = getCompanyByDomain(domain,companyUuid);
		if(company == null){
			throw new TServerException("该公司不存在");
		}
		PartnerInfo partner = getPartnerInfo(domain,partnerInfo.getPhone(),partnerInfo.getSystemId(),companyUuid);
		if(partner == null){
			throw new TServerException("账号不存在或已被禁用");
		}
		String code = Integer.toString(new Random().nextInt(900000)+100000);

		String systemName = SystemIdEnum.getByCode(partnerInfo.getSystemId()).getName();

		String messageContent = "【"+systemName+"】您的短信验证码是"+ code +",本条短信用于用户修改密码，有效时间3分钟，请勿泄露。";

		this.sendAndSaveSmsmsg(partnerInfo.getPhone(), messageContent, QfSmsTemplateEnum.SMS_EDIT_PWD.getId(), 
				SMSTypeEnum.TYPE_12.getDes(), partnerInfo.getSystemId(), 
				companyUuid, code, company.getId(), code, "3");
		
		return code;
	}
	
	/**
	 * 发送短信，并插入短信发送记录，以及验证码表
	 * @param phone 电话号码
	 * @param messageContent 内容，仅插入使用
	 * @param msgId 消息ID
	 * @param smsDesc 消息类型描述
	 * @param systemId 系统ID，仅入库使用
	 * @param companyUuid 公司UUID
	 * @param code 校验码
	 * @param companyId 公司ID
	 * @param msgs 短信替换模板中的参数值
	 * @return
	 */
	@Override
	public boolean sendAndSaveSmsmsg(String phone, String messageContent, String msgId, String smsDesc,
			String systemId, String companyUuid,  String code, Long companyId, String...msgs) {

		if(StringUtils.isEmpty(phone)) {
			return false;
		}
		
		Map<String, String> smsSettingMap = null;
    	Map<String, String> qfSmsMap = new HashMap<>();
    	for(int i = 0, j = msgs.length; i < j; i ++) {
    		qfSmsMap.put("key" + (i + 1), msgs[i]);
    	}
		//发送消息
		Map<String, Object> returnMap = smsUtil.sendMessage(messageContent,
				phone, msgId, smsSettingMap,qfSmsMap);
		boolean sendStatus = (Boolean) returnMap.get("sendStatus");
		String sendRes = String.valueOf(returnMap.get("sendRes"));
		//添加进历史表
		SmsHistoryDto history = new SmsHistoryDto();
		history.setContent(messageContent);
		history.setReceiver(phone);
		history.setMerchantId(companyId);
		history.setSender("qiaofang");
		history.setRemark(smsDesc);
		history.setCreateTime(new Date());
		history.setCreateUserId(0l);
		String state = sendStatus == true ? SendStatusEnum.SUCCESS.getNo():SendStatusEnum.FAILURE.getNo();
		history.setSendStatus(state);
		history.setSendRes(sendRes);
		smsHistoryMapper.add(history);
		//新的方法已使用redis进行判断，记录只是为了兼容老方法
		if(sendStatus && StringUtils.isNotBlank(code)){//发送成功, 且验证码不为空
			ValidateCodeDto dto = new ValidateCodeDto();
			dto.setAccountNo(phone);
			dto.setValidateCode(code);
			dto.setStatus(SendStatusEnum.SUCCESS.getNo());
			dto.setSystemId(systemId);
			dto.setDomain("");
			dto.setCompanyUuid(companyUuid);
			mapper.add(dto);
			return true;
		}
		return sendStatus;
	}

	//根据域名查询公司
	private Company getCompanyByDomain(String domain,String companyUuid){
		CompanyDto cDto = new CompanyDto();
		// todo 审核条件去掉
		//cDto.setStatus("1");//审核状态：0待审核1审核通过2审核失败
        if(StringUtils.isEmpty(companyUuid)){
            cDto.setDomain(domain);
        }else{
            cDto.setCompanyUuid(companyUuid);
        }
		cDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		List<Company> lists = companyService.selectListByDto(cDto);
		if(lists.size() > 0){
			return lists.get(0);
		}else{
			return null;
		}
	}

	/**
	 * 根据域名查询用户是否存在
	 * @param domain
	 * @param phone
	 * @return
	 */
	private PartnerInfo getPartnerInfo(String domain,String phone,String systemType,String companyUuid){
		List<PartnerInfo> list =  partnerInfoService.getRegisterPartner(domain,phone,systemType,companyUuid);
		if(list != null && list.size() > 0){
			return list.get(0);
		}else{
			return null;
		}
	}

}
